from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from email.mime.text import MIMEText
import smtplib
import ssl
import logging

password = 'G@9742ns'
server_email = 'no-reply@gnstec.com.hk'


logger = logging.getLogger(__name__)

### from IO system ###
def emailAction(subject, address, cc_str, html):
    context = ssl.create_default_context()
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject

    msg['From'] = server_email

    head = (MIMEText(html, "html"))
    msg.attach(head)
    msg['To'] = address
    msg['Cc'] = cc_str
    try:
        mailserver = smtplib.SMTP('smtp.office365.com', 587)
        mailserver.starttls()
        mailserver.ehlo()
        mailserver.login(server_email, password)
        mailserver.sendmail(server_email, address, msg.as_string())
        logger.debug(f"email sent to {address}")

    except Exception as ex:
        logger.critical(ex)
        logger.critical(f"fail email sent to {address}")

    finally:
        if mailserver:
            mailserver.quit()
    return

def send_email(recipient_email, subject, message):
    from_addr = formataddr(("CEWS", server_email))
    to_addr = recipient_email

    msg = MIMEText(message, 'plain')
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = subject

    smtp_server = 'smtp.office365.com'  
    smtp_port = 587  

    try:
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()
        server.ehlo()
        server.login(server_email, password)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
        print('邮件发送成功')
    except Exception as e:
        print('邮件发送失败:', str(e))

def email(address, html,blNumber):
    context = ssl.create_default_context()
    msg = MIMEMultipart('alternative')
    msg['Subject'] = f"提單編號: {blNumber} 登記記錄"

    msg['From'] = server_email

    head = (MIMEText(html, "html"))
    msg.attach(head)
    msg['To'] = address

    try:
        mailserver = smtplib.SMTP('smtp.office365.com', 587)
        mailserver.starttls()
        mailserver.ehlo()
        mailserver.login(server_email, password)
        mailserver.sendmail(server_email, address, msg.as_string())
        logger.debug(f"email sent to {address}")

    except Exception as ex:
        logger.critical(ex)
        logger.critical(f"fail email sent to {address}")

    finally:
        if mailserver:
            mailserver.quit()
    return

